﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class ResourceUpdateFile {

	public class FileData {
		public string name;
		public string relativePath;
		public string md5;
		public bool isInStreamingAssets;

		public FileData(string name, string relativePath, string md5, bool isInStreamingAssets) {
			this.name = name;
			this.relativePath = relativePath;
			this.md5 = md5;
			this.isInStreamingAssets = isInStreamingAssets;
		}
	}

	private Dictionary<string, FileData> dicFileData = new Dictionary<string, FileData> ();
	private string versionStr;

	public bool Load(string path) {
		string absolutePath;
		bool isExist = UnityPath.TryGetFile (path, out absolutePath);
		if (!isExist) {
			return false;		
		}

		string[] files = File.ReadAllLines (absolutePath);

		// version
		string[] splitStr0 = files[0].Split('|');
		if (splitStr0.Length == 2 && splitStr0 [0] == "version") {
			versionStr = splitStr0 [1];
		}

		// title


		for (int i = 2; i < files.Length; ++i) {
			string[] splitStr = files [i].Split ('|');
			if (splitStr.Length == 4) {
				bool isInStreamingAssets;
				if(!bool.TryParse(splitStr[3], out isInStreamingAssets)) {
					Debug.LogWarning ("ResourceUpdateFile parse: bool parse error! line number is: " + i);
					Unload ();
					return false;
				}
				FileData data = new FileData (splitStr [0], splitStr [1], splitStr [2], isInStreamingAssets);
				dicFileData.Add (splitStr [1], data);
			} else {
				Debug.LogWarning ("ResourceUpdateFile parse: line elements is not match! line number is: " + i);
				Unload ();
				return false;
			}
		}

		return true;
	}

	public void Unload() {
		dicFileData.Clear ();
	}

	public bool GetFilePath(string filePath, out bool isInStreamingAssets) {
		FileData data = null;
		if (dicFileData.TryGetValue (filePath, out data)) {
			isInStreamingAssets = data.isInStreamingAssets;
			return true;
		}

		isInStreamingAssets = false;
		return false;
	}

	public bool GetFileData(string filePath, out FileData data) {
		if (dicFileData.TryGetValue (filePath, out data)) {
			return true;
		}

		return false;
	}
}
